from ncatbot.plugin import BasePlugin, CompatibleEnrollment
from ncatbot.core.message import GroupMessage, PrivateMessage
from ncatbot.utils.logger import get_log
from ncatbot.utils.config import config
from ncatbot.core import (
    MessageChain,  # 消息链，用于组合多个消息元素
    Text,          # 文本消息
    Reply,         # 回复消息
    At,            # @某人
    AtAll,         # @全体成员
    Dice,          # 骰子
    Face,          # QQ表情
    Image,         # 图片
    Json,          # JSON消息
    Music,         # 音乐分享 (网易云, QQ 音乐等)
    CustomMusic,   # 自定义音乐分享
    Record,        # 语音
    Rps,           # 猜拳
    Video,         # 视频
    File,          # 文件（已弃用）
)
import time
import datetime
import asyncio
from collections import defaultdict
import os
import json

bot = CompatibleEnrollment  # 兼容回调函数注册器
_log = get_log()

class TestPlugin(BasePlugin):
    name = "TestPlugin" # 插件名称
    version = "0.0.5" # 插件版本

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 用于存储用户发送图片的记录，格式: {group_id: {user_id: [(timestamp, count)]}}
        self.image_records = defaultdict(lambda: defaultdict(list))
        # 图片计数窗口时间（秒）
        self.image_window = 60  # 1分钟内
        # 触发禁言的图片数量
        self.image_threshold = 4
        # 禁言时长（秒）- 第一次
        self.ban_duration_first = 600  # 10分钟
        # 禁言时长（秒）- 第二次
        self.ban_duration_second = 3600  # 1小时
        # 修改刷屏记录格式
        # 由 defaultdict(lambda: defaultdict(int)) 改为 列表+字典格式
        # 格式: [{group_id: 群号, users: [{user_id: QQ号, number: 次数}, ...]}]
        self.spam_counts = []
        # 黑名单
        self.blacklist = set()
        # 全员禁言状态
        self.all_mute_groups = set()
        # 默认禁言/解禁时间 - 设置为晚上23点和早上7点
        self.mute_hour = 23
        self.mute_minute = 0
        self.unmute_hour = 7
        self.unmute_minute = 0
        # 上次检测时间
        self.last_check_minute = -1
        # root用户ID列表
        self.root_user = 2337011367  # 替换为实际的root用户ID
        # 群组ID列表
        self.group_ids = [957509833]
        self.check_image_floodStatus=True
        self.check_at_ownerStatus=True
        
        # 违规词检测功能相关变量
        self.ad_keywords = []  # 违规词关键词
        self.ad_ban_duration = 600  # 发违规词禁言时长(秒)，默认10分钟
        self.ad_records = defaultdict(lambda: defaultdict(int))  # 记录用户发违规词次数 {group_id: {user_id: count}}
        self.check_ad_status = True  # 违规词检测状态

        #留言板
        self.message_records = defaultdict(list)  # 留言板，格式: {group_id: [(user_id, message), ...]}
    
    @bot.group_event()
    async def on_group_event(self, msg: GroupMessage):
        # 定义的回调函数
        if msg.group_id not in self.group_ids:
            return
        
        _log.info(f"群聊消息: {msg.raw_message}")
        

        # 检测是否@机器人
        at_robot = await self.check_at_robot(msg)
        if at_robot:
            return

        # 检测用户是否为管理员或群主
        is_admin = await self.check_user_permission(msg.group_id, msg.user_id)

        # 检测用户是否为root用户
        is_root = msg.user_id==self.root_user

        ###超级管理员和管理员共有的功能
        if is_admin or is_root:

            if msg.raw_message=="刷屏检测":
                feature_list = "◆◆∞∞刷屏检测∞∞◆◆\n"
                feature_list += ".➹.设置刷屏时间 (秒)\n"
                feature_list += ".➹.设置刷屏数量 (张)\n"
                feature_list += ".➹.查看刷屏设置\n"
                feature_list += ".➹.刷屏清除 (QQ号/@用户)\n"
                feature_list += ".➹.查看/清空刷屏记录\n"
                feature_list += "Tipe:发送文字使用功能\n"
                feature_list += "━━━━━━━━━━━\n"
                feature_list += f"你的身份：{'群主' if is_root else '管理员'}\n"
                feature_list += "━━━━━━━━━━━"
                await self.api.post_group_msg(msg.group_id, text=feature_list)
                return
            
            if msg.raw_message=="禁言功能":
                feature_list = "◆◆∞∞禁言功能∞∞◆◆\n"
                feature_list += ".➹.开启/解除全员禁言\n"
                feature_list += ".➹.设置禁言时间\n"
                feature_list += ".➹.查看禁言设置\n"
                feature_list += "Tipe:发送文字使用功能\n"
                feature_list += "━━━━━━━━━━━\n"
                feature_list += f"你的身份：{'群主' if is_root else '管理员'}\n"
                feature_list += "━━━━━━━━━━━"
                await self.api.post_group_msg(msg.group_id, text=feature_list)
                return
            
            if msg.raw_message=="违规检测":
                feature_list = "◆◆∞∞违规检测∞∞◆◆\n"
                feature_list += ".➹.开启/关闭违规词检测\n"
                feature_list += ".➹.添加/删除违规词+XX\n"
                feature_list += ".➹.查看/清空违规词列表\n"
                feature_list += ".➹.查看违规词处罚设置\n"
                feature_list += ".➹.查看/清空违规词记录\n"
                feature_list += ".➹.清除违规词记录@XXX\n"
                feature_list += ".➹.设置违规词处罚+(禁言分钟)\n"
                feature_list += "Tipe:发送文字使用功能\n"
                feature_list += "━━━━━━━━━━━\n"
                feature_list += f"你的身份：{'群主' if is_root else '管理员'}\n"
                feature_list += "━━━━━━━━━━━"
                await self.api.post_group_msg(msg.group_id, text=feature_list)
                return
            
            if msg.raw_message=="撤回功能":
                feature_list = "◆◆∞∞撤回功能∞∞◆◆\n"
                feature_list += ".➹.撤回消息+数量\n"
                feature_list += ".➹.撤回消息@用户+数量\n"
                feature_list += "Tipe:发送文字使用功能\n"
                feature_list += "━━━━━━━━━━━\n"
                feature_list += f"你的身份：{'群主' if is_root else '管理员'}\n"
                feature_list += "━━━━━━━━━━━"
                await self.api.post_group_msg(msg.group_id, text=feature_list)
                return
            
            # 实现撤回消息功能
            if msg.raw_message.startswith("撤回消息"):
                try:
                    # 默认参数
                    count = 5  # 默认撤回5条
                    target_user_id = None  # 默认不针对特定用户
                    
                    # 解析命令
                    parts = msg.raw_message.split("+")
                    
                    # 检查是否包含@用户
                    has_at = False
                    
                    # 从消息数组中检查@
                    if isinstance(msg.message, list):
                        for item in msg.message:
                            if isinstance(item, dict) and item.get('type') == 'at' and 'data' in item:
                                at_qq = item.get('data', {}).get('qq')
                                if at_qq:
                                    target_user_id = int(at_qq)
                                    has_at = True
                                    break
                    
                    # 如果没有找到@，尝试从原始消息中解析CQ码
                    if not has_at:
                        at_pos = msg.raw_message.find("[CQ:at,qq=")
                        if at_pos != -1:
                            # 找到CQ码结束位置
                            end_pos = msg.raw_message.find("]", at_pos)
                            if end_pos != -1:
                                # 提取QQ号
                                cq_code = msg.raw_message[at_pos:end_pos+1]
                                qq_start = cq_code.find("qq=") + 3
                                qq_end = cq_code.find("]", qq_start)
                                if qq_end == -1:
                                    qq_end = len(cq_code)
                                target_user_id = int(cq_code[qq_start:qq_end])
                                has_at = True
                    
                    # 处理数量参数
                    if len(parts) >= 2:
                        last_part = parts[-1].strip()
                        # 如果有@用户，那么数量应该是在@之后的部分
                        if has_at:
                            # 检查最后一部分是否为数字
                            try:
                                count = int(last_part)
                                if count <= 0:
                                    await self.api.post_group_msg(
                                        group_id=msg.group_id,
                                        text="撤回条数必须大于0"
                                    )
                                    return
                            except ValueError:
                                # 如果不是数字，使用默认值5
                                count = 5
                        else:
                            # 如果没有@用户，就是普通的撤回消息+数量格式
                            try:
                                count = int(last_part)
                                if count <= 0:
                                    await self.api.post_group_msg(
                                        group_id=msg.group_id,
                                        text="撤回条数必须大于0"
                                    )
                                    return
                            except ValueError:
                                await self.api.post_group_msg(
                                    group_id=msg.group_id,
                                    text="格式错误，正确格式：撤回消息+数量 或 撤回消息@用户+数量"
                                )
                                return
                    
                    # 获取群消息历史
                    history = await self.api.get_group_msg_history(
                        group_id=msg.group_id,
                        message_seq=0,  # 从最新的消息开始
                        count=100, # 获取足够多的消息以便筛选
                        reverse_order=True  # 最新的消息在前
                    )
                    if not history or 'data' not in history or 'messages' not in history['data']:
                        await self.api.post_group_msg(
                            group_id=msg.group_id,
                            text="获取消息历史失败，无法执行撤回操作"
                        )
                        return
                    # 获取消息列表
                    messages = history['data']['messages']
                    print(messages,count)
                    # 筛选消息（如果指定了目标用户）
                    if target_user_id:
                        filtered_messages = [msg for msg in messages if msg.get('user_id') == target_user_id and msg.get('raw_message')!='']
                    else:
                        filtered_messages = [msg for msg in messages if msg.get('sender').get('role') == 'member'and msg.get('raw_message')!='']
                    # 限制撤回数量
                    messages_to_recall = filtered_messages[:count]
                    print(messages_to_recall,count)
                    # 执行撤回
                    recall_count = 0
                    for message in messages_to_recall:
                        message_id = message.get('message_id')
                        print('message_id',message_id)
                        if message_id:
                            try:
                                # 尝试撤回消息
                                recall_result = await self.api.delete_msg(message_id=message_id)
                                if recall_result and recall_result.get('status') == 'ok':
                                    recall_count += 1
                                await asyncio.sleep(0.5)  # 添加延迟，避免过快撤回导致限制
                            except Exception as e:
                                _log.error(f"撤回消息 {message_id} 失败: {e}")
                                continue
                    
                    # 发送结果通知
                    if target_user_id:
                        await self.api.post_group_msg(
                            group_id=msg.group_id,
                            text=f"已撤回用户 {target_user_id} 的 {recall_count} 条消息"
                        )
                    else:
                        await self.api.post_group_msg(
                            group_id=msg.group_id,
                            text=f"已撤回 {recall_count} 条消息"
                        )
                    
                except Exception as e:
                    _log.error(f"撤回消息出错: {e}")
                    import traceback
                    _log.error(traceback.format_exc())
                    await self.api.post_group_msg(
                        group_id=msg.group_id,
                        text=f"撤回消息出错: {str(e)}"
                    )
                return
                

            
            if msg.raw_message == "查看刷屏记录":
                try:
                    # 添加调试日志
                    _log.info(f"查看刷屏记录 - 刷屏记录: {self.spam_counts}")
                    _log.info(f"查看刷屏记录 - 当前群号: {msg.group_id}")
                    # 查找当前群的刷屏记录
                    group_records = None
                    for group_data in self.spam_counts:
                        if group_data['group_id'] == msg.group_id:
                            group_records = group_data
                            break
                    if group_records and group_records['users']:
                        record_str = f"当前群聊 {msg.group_id} 的刷屏记录：\n"
                        for user_data in group_records['users']:
                            record_str += f"用户 {user_data['user_id']}：{user_data['number']}次\n"
                        await self.api.post_group_msg(msg.group_id, text=record_str)
                    else:
                        await self.api.post_group_msg(msg.group_id, text="当前群没有刷屏记录")
                except Exception as e:
                    _log.error(f"查看刷屏记录出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"查看刷屏记录出错: {str(e)}")
                return
            
            if msg.raw_message == "清空刷屏记录":
                try:
                    # 查找并移除当前群的刷屏记录
                    has_removed = False
                    for i, group_data in enumerate(self.spam_counts):
                        if group_data['group_id'] == msg.group_id:
                            self.spam_counts.pop(i)
                            has_removed = True
                            break
                    # 清空当前群的图片记录
                    if msg.group_id in self.image_records:
                        del self.image_records[msg.group_id]
                        has_removed = True
                    
                    if has_removed:
                        # 保存更新后的数据
                        await self.save_spam_data()
                        await self.api.post_group_msg(msg.group_id, text="已清空本群的刷屏记录")
                    else:
                        await self.api.post_group_msg(msg.group_id, text="当前群没有刷屏记录")
                except Exception as e:
                    _log.error(f"清空刷屏记录出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"清空刷屏记录出错: {str(e)}")
                return
            
            if msg.raw_message.startswith("刷屏清除"):
                try:
                    # 添加调试日志
                    _log.info(f"刷屏清除 - 当前刷屏记录: {self.spam_counts}")
                    _log.info(f"刷屏清除 - 当前群号: {msg.group_id} (类型: {type(msg.group_id)})")
                    
                    # 检查是否包含CQ:at代码
                    at_pos = msg.raw_message.find("[CQ:at,qq=")
                    if at_pos != -1:
                        # 找到CQ码结束位置
                        end_pos = msg.raw_message.find("]", at_pos)
                        if end_pos != -1:
                            # 提取QQ号
                            cq_code = msg.raw_message[at_pos:end_pos+1]
                            qq_start = cq_code.find("qq=") + 3
                            qq_end = cq_code.find("]", qq_start)
                            if qq_end == -1:
                                qq_end = len(cq_code)
                            user_id = int(cq_code[qq_start:qq_end])
                            
                            # 在新格式中查找该用户的记录
                            has_record = False
                            for group_data in self.spam_counts:
                                if group_data['group_id'] == msg.group_id:
                                    # 查找用户
                                    for i, user_data in enumerate(group_data['users']):
                                        if user_data['user_id'] == user_id:
                                            # 找到用户，删除记录
                                            group_data['users'].pop(i)
                                            has_record = True
                                            break
                                    break
                            
                            # 清除图片记录
                            if msg.group_id in self.image_records and user_id in self.image_records[msg.group_id]:
                                del self.image_records[msg.group_id][user_id]
                                has_record = True
                            
                            if has_record:
                                # 保存更新后的数据
                                await self.save_spam_data()
                                await self.api.post_group_msg(group_id=msg.group_id, text=f"已清除用户 {user_id} 在本群的刷屏记录")
                            else:
                                await self.api.post_group_msg(group_id=msg.group_id, text=f"用户 {user_id} 在本群没有刷屏记录")
                        else:
                            await self.api.post_group_msg(group_id=msg.group_id, text="格式错误，正确格式：刷屏清除[CQ:at,qq=QQ号]")
                    else:
                        # 保留原有的空格分隔QQ号的方式作为备选
                        parts = msg.raw_message.split()
                        if len(parts) >= 2:
                            user_id = int(parts[1])
                            
                            # 在新格式中查找该用户的记录
                            has_record = False
                            for group_data in self.spam_counts:
                                if group_data['group_id'] == msg.group_id:
                                    # 查找用户
                                    for i, user_data in enumerate(group_data['users']):
                                        if user_data['user_id'] == user_id:
                                            # 找到用户，删除记录
                                            group_data['users'].pop(i)
                                            has_record = True
                                            break
                                    break
                            
                            # 清除图片记录
                            if msg.group_id in self.image_records and user_id in self.image_records[msg.group_id]:
                                del self.image_records[msg.group_id][user_id]
                                has_record = True
                            
                            if has_record:
                                # 保存更新后的数据
                                await self.save_spam_data()
                                await self.api.post_group_msg(group_id=msg.group_id, text=f"已清除用户 {user_id} 在本群的刷屏记录")
                            else:
                                await self.api.post_group_msg(group_id=msg.group_id, text=f"用户 {user_id} 在本群没有刷屏记录")
                        else:
                            await self.api.post_group_msg(group_id=msg.group_id, text="格式错误，正确格式：刷屏清除 QQ号 或 刷屏清除[CQ:at,qq=QQ号]")
                except Exception as e:
                    _log.error(f"清除刷屏记录出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"清除刷屏记录出错: {str(e)}")
                return
            
            if msg.raw_message == "测试":
                await self.api.post_group_msg(msg.group_id, text="机器人正在运行中")
                return
            
            # 手动触发全员禁言命令
            if msg.raw_message == '开启全员禁言':
                await self.set_group_all_mute(msg.group_id, True)
                return
                
            # 手动触发解除全员禁言命令
            if msg.raw_message == '解除全员禁言':
                await self.set_group_all_mute(msg.group_id, False)
                return
                
            # 查看禁言时间设置
            if msg.raw_message == '查看禁言设置':
                mute_time = f"{self.mute_hour:02d}:{self.mute_minute:02d}"
                unmute_time = f"{self.unmute_hour:02d}:{self.unmute_minute:02d}"
                message = f"当前全员禁言设置为每天 {mute_time} 开启，{unmute_time} 解除。"
                await self.api.post_group_msg(group_id=msg.group_id, text=message)
                return
                
            # 设置自定义禁言/解禁时间 (仅管理员可用)
            if msg.raw_message.startswith('设置禁言时间'):
                try:
                    # 格式：设置禁言时间 HH:MM HH:MM
                    parts = msg.raw_message.split()
                    if len(parts) == 3:
                        mute_time = parts[1]  # 格式 HH:MM
                        unmute_time = parts[2]  # 格式 HH:MM
                        
                        # 解析时间
                        mute_hour, mute_minute = map(int, mute_time.split(':'))
                        unmute_hour, unmute_minute = map(int, unmute_time.split(':'))
                        
                        # 安全检测
                        if 0 <= mute_hour < 24 and 0 <= mute_minute < 60 and 0 <= unmute_hour < 24 and 0 <= unmute_minute < 60:
                            message = f"全员禁言时间已设置为 {mute_time}，解除时间为 {unmute_time}"
                            
                            # 更新实例变量
                            self.mute_hour = mute_hour
                            self.mute_minute = mute_minute
                            self.unmute_hour = unmute_hour
                            self.unmute_minute = unmute_minute
                            
                            # 更新定时任务
                            await self.update_scheduled_tasks()
                            
                            await self.api.post_group_msg(group_id=msg.group_id, text=message)
                            return
                        else:
                            await self.api.post_group_msg(group_id=msg.group_id, text="时间格式错误，请使用24小时制，例如：设置禁言时间 23:00 07:00")
                            return
                    else:
                        await self.api.post_group_msg(group_id=msg.group_id, text="格式错误，正确格式：设置禁言时间 23:00 07:00")
                        return
                except Exception as e:
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"设置时间出错：{str(e)}\n正确格式：设置禁言时间 23:00 07:00")
                    return
            
            # 设置刷屏刷屏检测时间
            if msg.raw_message.startswith("设置刷屏时间"):
                try:
                    parts = msg.raw_message.split()
                    if len(parts) >= 2:
                        try:
                            window_seconds = int(parts[1])
                            if window_seconds > 0:
                                self.image_window = window_seconds
                                await self.save_config("image_window", window_seconds)
                                await self.api.post_group_msg(msg.group_id, text=f"已设置刷屏刷屏检测时间为 {window_seconds} 秒")
                            else:
                                await self.api.post_group_msg(msg.group_id, text="时间窗口必须大于0秒")
                        except ValueError:
                            await self.api.post_group_msg(msg.group_id, text="格式错误，请输入整数秒数")
                    else:
                        await self.api.post_group_msg(msg.group_id, text="格式错误，正确格式：设置刷屏时间 秒数")
                except Exception as e:
                    _log.error(f"设置刷屏时间出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"设置刷屏时间出错: {str(e)}")
                return
            
            # 设置触发禁言的图片数量
            if msg.raw_message.startswith("设置刷屏数量"):
                try:
                    parts = msg.raw_message.split()
                    if len(parts) >= 2:
                        try:
                            threshold = int(parts[1])
                            if threshold > 0:
                                self.image_threshold = threshold
                                await self.save_config("image_threshold", threshold)
                                await self.api.post_group_msg(msg.group_id, text=f"已设置触发禁言的图片数量为 {threshold} 张")
                            else:
                                await self.api.post_group_msg(msg.group_id, text="数量必须大于0")
                        except ValueError:
                            await self.api.post_group_msg(msg.group_id, text="格式错误，请输入整数")
                    else:
                        await self.api.post_group_msg(msg.group_id, text="格式错误，正确格式：设置刷屏数量 数量")
                except Exception as e:
                    _log.error(f"设置刷屏数量出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"设置刷屏数量出错: {str(e)}")
                return
            
            # 查看当前刷屏设置
            if msg.raw_message == "查看刷屏设置":
                try:
                    settings_str = f"当前刷屏设置：\n"
                    settings_str += f"1. 刷屏检测时间：{self.image_window} 秒\n"
                    settings_str += f"2. 触发禁言的图片数量：{self.image_threshold} 张\n"
                    settings_str += f"3. 第一次刷屏禁言时长：{self.ban_duration_first//60} 分钟\n"
                    settings_str += f"4. 第二次刷屏禁言时长：{self.ban_duration_second//3600} 小时\n"
                    settings_str += f"5. 第三次刷屏将被踢出并拉黑"
                    await self.api.post_group_msg(msg.group_id, text=settings_str)
                except Exception as e:
                    _log.error(f"查看刷屏设置出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"查看刷屏设置出错: {str(e)}")
                return
            
            # 查看当前禁言设置
            if msg.raw_message == "查看违规词设置":
                settings_str = f"当前违规词设置：\n"
                settings_str += f"1. 违规词检测状态：{'开启' if self.check_ad_status else '关闭'}\n"
                settings_str += f"2. 违规词禁言时长：{self.ad_ban_duration//60} 分钟\n"
                await self.api.post_group_msg(msg.group_id, text=settings_str)
                return
            
            # 设置违规词禁言时长 
            if msg.raw_message.startswith("设置违规词处罚"):
                try:
                     #设置违规词处罚+30 (+号连接)
                    if "+" in msg.raw_message:
                        # 处理 "设置违规词处罚+30" 格式
                        parts = msg.raw_message.split("+")
                        if len(parts) >= 2:
                            try:
                                minutes = int(parts[1].strip())
                                ban_duration = minutes * 60  # 转换为秒
                                if ban_duration > 0:
                                    self.ad_ban_duration = ban_duration
                                    await self.save_config("ad_ban_duration", ban_duration)
                                    await self.api.post_group_msg(msg.group_id, text=f"已设置违规词禁言时长为 {minutes} 分钟")
                                else:
                                    await self.api.post_group_msg(msg.group_id, text="禁言时长必须大于0分钟")
                            except ValueError:
                                await self.api.post_group_msg(msg.group_id, text="格式错误，请输入整数分钟数")
                        else:
                            await self.api.post_group_msg(msg.group_id, text="格式错误，正确格式：设置违规词处罚+分钟数")
                    else:
                        await self.api.post_group_msg(msg.group_id, text="格式错误，正确格式：设置违规词处罚+分钟数")
                except Exception as e:
                    _log.error(f"设置违规词处罚出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"设置违规词处罚出错: {str(e)}")
                return
            
            # 查看违规词处罚
            if msg.raw_message == "查看违规词处罚设置":
                settings_str = f"当前违规词处罚设置：\n"
                settings_str += f"1. 违规词禁言时长：{self.ad_ban_duration//60} 分钟\n"
                await self.api.post_group_msg(msg.group_id, text=settings_str)
                return
            
            # 查看违规词记录
            if msg.raw_message == "查看违规词记录":
                try:
                    if not self.ad_records:
                        await self.api.post_group_msg(msg.group_id, text="当前没有违规词记录")
                        return
                    records_str = "当前违规词记录：\n"
                    for group_id, user_data in self.ad_records.items():
                        records_str += f"群 {group_id}:\n"
                        for user_id, count in user_data.items():
                            records_str += f"用户 {user_id}: {count} 次\n"
                    await self.api.post_group_msg(msg.group_id, text=records_str)
                except Exception as e:
                    _log.error(f"查看违规词记录出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"查看违规词记录出错: {str(e)}")
                return
            
            # 清空违规词记录
            if msg.raw_message == "清空违规词记录":
                try:
                    self.ad_records.clear()
                    await self.save_config("ad_records", self.ad_records)
                    await self.api.post_group_msg(msg.group_id, text="已清空违规词记录")
                except Exception as e:
                    _log.error(f"清空违规词记录出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"清空违规词记录出错: {str(e)}")
            
            # 清除违规词记录
            if msg.raw_message.startswith("清除违规词记录"):
                try:
                    # 检查消息中是否包含@标记
                    has_at = False
                    at_user_id = None
                    # 从消息数组中检查@
                    if isinstance(msg.message, list):
                        for item in msg.message:
                            if isinstance(item, dict) and item.get('type') == 'at' and 'data' in item:
                                at_user_id = item.get('data', {}).get('qq')
                                if at_user_id:
                                    has_at = True
                                    at_user_id = int(at_user_id)
                                    break
                    # 如果没有找到@，也尝试从原始消息中解析CQ码
                    if not has_at:
                        at_pos = msg.raw_message.find("[CQ:at,qq=")
                        if at_pos != -1:
                            # 找到CQ码结束位置
                            end_pos = msg.raw_message.find("]", at_pos)
                            if end_pos != -1:
                                # 提取QQ号
                                cq_code = msg.raw_message[at_pos:end_pos+1]
                                qq_start = cq_code.find("qq=") + 3
                                qq_end = cq_code.find("]", qq_start)
                                if qq_end == -1:
                                    qq_end = len(cq_code)
                                at_user_id = int(cq_code[qq_start:qq_end])
                                has_at = True
                    
                    if has_at and at_user_id:
                        # 在违规词记录中查找该用户的记录
                        has_record = False
                        
                        # 检查当前群的记录
                        if msg.group_id in self.ad_records and at_user_id in self.ad_records[msg.group_id]:
                            del self.ad_records[msg.group_id][at_user_id]
                            has_record = True
                        
                        if has_record:
                            # 保存更新后的数据
                            await self.save_config("ad_records", dict(self.ad_records))  # 转换为普通字典再保存
                            await self.api.post_group_msg(
                                group_id=msg.group_id, 
                                text=f"已清除用户 {at_user_id} 在本群的违规词记录"
                            )
                        else:
                            await self.api.post_group_msg(
                                group_id=msg.group_id, 
                                text=f"用户 {at_user_id} 在本群没有违规词记录"
                            )
                    else:
                        await self.api.post_group_msg(
                            group_id=msg.group_id, 
                            text="请@要清除记录的用户，格式：清除违规词记录@用户"
                        )
                except Exception as e:
                    _log.error(f"清除违规词记录出错: {e}")
                    import traceback
                    _log.error(traceback.format_exc())
                    await self.api.post_group_msg(
                        group_id=msg.group_id, 
                        text=f"清除违规词记录出错: {str(e)}"
                    )
                return

            # 设置违规词检测状态
            if msg.raw_message == "开启违规词检测":
                self.check_ad_status = True
                await self.save_config("check_ad_status", True)
                await self.api.post_group_msg(msg.group_id, text="已开启违规词检测功能")
                return
            if msg.raw_message == "关闭违规词检测":
                self.check_ad_status = False
                await self.save_config("check_ad_status", False)
                await self.api.post_group_msg(msg.group_id, text="已关闭违规词检测功能")
                return
            # 添加违规词
            if msg.raw_message.startswith("添加违规词+"):
                try:
                    # 从"添加违规词+"后截取关键词
                    keyword = msg.raw_message[6:].strip()  # "添加违规词+"有6个字符
                    if keyword:
                        if keyword not in self.ad_keywords:
                            self.ad_keywords.append(keyword)
                            await self.save_config("ad_keywords", self.ad_keywords)
                            await self.api.post_group_msg(msg.group_id, text=f"已添加违规词: {keyword}")
                        else:
                            await self.api.post_group_msg(msg.group_id, text=f"违规词 {keyword} 已存在")
                    else:
                        await self.api.post_group_msg(msg.group_id, text="违规词不能为空，格式：添加违规词+关键词")
                except Exception as e:
                    _log.error(f"添加违规词出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"添加违规词出错: {str(e)}")
                return

            # 删除违规词功能 - 仅支持+连接方式
            if msg.raw_message.startswith("删除违规词+"):
                try:
                    # 从"删除违规词+"后截取关键词
                    keyword = msg.raw_message[6:].strip()  # "删除违规词+"有6个字符
                    if keyword:
                        if keyword in self.ad_keywords:
                            self.ad_keywords.remove(keyword)
                            await self.save_config("ad_keywords", self.ad_keywords)
                            await self.api.post_group_msg(msg.group_id, text=f"已删除违规词: {keyword}")
                        else:
                            await self.api.post_group_msg(msg.group_id, text=f"违规词 {keyword} 不存在")
                    else:
                        await self.api.post_group_msg(msg.group_id, text="请指定要删除的违规词，格式：删除违规词+关键词")
                except Exception as e:
                    _log.error(f"删除违规词出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"删除违规词出错: {str(e)}")
                return

            # 查看违规词功能
            if msg.raw_message == "查看违规词列表":
                try:
                    if not self.ad_keywords:
                        await self.api.post_group_msg(msg.group_id, text="当前没有设置任何违规词")
                        return
                    keywords_str = "\n".join(f"{i+1}. {keyword}" for i, keyword in enumerate(self.ad_keywords))
                    await self.api.post_group_msg(msg.group_id, text=f"当前违规词列表 (共{len(self.ad_keywords)}个):\n{keywords_str}")
                except Exception as e:
                    _log.error(f"查看违规词出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"查看违规词出错: {str(e)}")
                return
            
            # 清空违规词列表
            if msg.raw_message == "清空违规词列表":
                try:
                    self.ad_keywords = []
                    await self.save_config("ad_keywords", self.ad_keywords)
                    await self.api.post_group_msg(msg.group_id, text="已清空违规词列表")
                except Exception as e:
                    _log.error(f"清空违规词列表出错: {e}")
                    await self.api.post_group_msg(group_id=msg.group_id, text=f"清空违规词列表出错: {str(e)}")
                return

        ###超级管理员的功能
        if is_root:
            # 检测关键词并调用API发送图片
            status=await self.check_keywords_and_send_image(msg)
            if status==True:
                return
            if msg.raw_message=="开启检测防刷屏":
                self.check_image_floodStatus=True
                await self.api.post_group_msg(msg.group_id, text="已开启检测防刷屏功能")
                return
            
            if msg.raw_message=="关闭检测防刷屏":
                self.check_image_floodStatus=False
                await self.api.post_group_msg(msg.group_id, text="已关闭检测防刷屏功能")
                return
            
            if msg.raw_message=="开启检测@群主":
                self.check_at_ownerStatus=True
                await self.api.post_group_msg(msg.group_id, text="已开启检测@群主功能")
                return
            
            if msg.raw_message=="关闭检测@群主":
                self.check_at_ownerStatus=False
                await self.api.post_group_msg(msg.group_id, text="已关闭检测@群主功能")
                return
            
            if msg.raw_message=="查看功能状态":
                await self.api.post_group_msg(msg.group_id, text=f"当前功能状态：\n检测防刷屏：{'开启' if self.check_image_floodStatus else '关闭'}\n检测@群主：{'开启' if self.check_at_ownerStatus else '关闭'}")
                return
            
            if msg.raw_message==("功能列表"):
                feature_list = "◆◆∞∞功能列表∞∞◆◆\n"
                feature_list += ".❁.刷屏检测丨禁言功能.❁.\n"
                feature_list += ".❁.违规检测丨撤回功能\n"
                feature_list += ".❁.其他功能\n"
                feature_list += "Tipe:发送文字介绍详情\n"
                feature_list += "━━━━━━━━━━━\n"
                feature_list += f"你的身份：群主\n"
                feature_list += "━━━━━━━━━━━"
                await self.api.post_group_msg(msg.group_id, text=feature_list)
                return
            
            if msg.raw_message==("其他功能"):
                feature_list = "◆◆∞∞其他功能∞∞◆◆\n"
                feature_list += ".➹.开启/关闭检测防刷屏\n"
                feature_list += ".➹.开启/关闭检测@群主\n"
                feature_list += ".➹.查看功能状态\n"
                feature_list += "Tipe:发送文字开启功能\n"
                feature_list += "━━━━━━━━━━━\n"
                feature_list += f"你的身份：群主\n"
                feature_list += "━━━━━━━━━━━"
                await self.api.post_group_msg(msg.group_id, text=feature_list)
                return
            
        ###管理员的功能
        if is_admin:
            if msg.raw_message==("功能列表"):
                feature_list = "◆◆∞∞功能列表∞∞◆◆\n"
                feature_list += ".❁.刷屏检测丨禁言功能.❁.\n"
                feature_list += ".❁.违规检测丨撤回功能\n"
                feature_list += "Tipe:发送文字介绍详情\n"
                feature_list += "━━━━━━━━━━━\n"
                feature_list += f"你的身份：管理员\n"
                feature_list += "━━━━━━━━━━━\n"
                await self.api.post_group_msg(msg.group_id, text=feature_list)
                return
        
                # 检测是否包含违规词
        if await self.check_advertisement(msg):
            return  # 如果是违规词且已处理，则不继续处理

        ###普通用户的功能    
        if is_admin==False and is_root==False:
            # 检测防刷屏
            if self.check_image_floodStatus==True:
                checkstatus=await self.check_image_flood(msg)
                if checkstatus==True:
                    return
                
            # 检测@群主
            if self.check_at_ownerStatus==True:
                checkstatus=await self.check_at_owner(msg)
                if checkstatus==True:
                    return

            if msg.raw_message==("功能列表"):
                feature_list = "◆◆∞∞功能列表∞∞◆◆\n"
                feature_list += ".❁.留言系统.❁.\n"
                feature_list += "Tipe:发送文字介绍详情\n"
                feature_list += "━━━━━━━━━━━\n"
                feature_list += f"你的身份：普通成员\n"
                feature_list += "━━━━━━━━━━━"
                await self.api.post_group_msg(msg.group_id, text=feature_list)
                return
            
            if msg.raw_message==("留言系统"):
                feature_list = "◆◆∞∞留言系统∞∞◆◆\n"
                feature_list += ".➹.留言+(留言内容)\n"
                feature_list += "Tipe:发送文字使用功能\n"
                feature_list += "━━━━━━━━━━━\n"
                feature_list += f"你的身份：普通成员\n"
                feature_list += "━━━━━━━━━━━"
                await self.api.post_group_msg(msg.group_id, text=feature_list)
                return
            

            if msg.raw_message.startswith("留言+"):
                # 提取留言内容
                content = msg.raw_message[3:].strip()
                if content:
                    try:
                        # 获取当前时间
                        current_time = int(time.time())
                        # 计算今天0点的时间戳
                        today = time.localtime(current_time)
                        day_start = time.mktime((today.tm_year, today.tm_mon, today.tm_mday, 0, 0, 0, 0, 0, 0))
                        
                        # 加载现有留言，确保是字典类型而不是列表
                        if not hasattr(self, "message_records"):
                            self.message_records = {}
                            # 尝试从配置加载
                            config = self.data.get("config", {})
                            if "message_records" in config:
                                self.message_records = config["message_records"]
                                
                        # 确保群号对应的键存在
                        if msg.group_id not in self.message_records:
                            self.message_records[msg.group_id] = []
                        
                        # 检查今日留言次数
                        user_today_messages = 0
                        for message in self.message_records[msg.group_id]:
                            if message.get("user_id") == msg.user_id and message.get("time", 0) >= day_start:
                                user_today_messages += 1
                        
                        # 判断是否超过限制
                        if user_today_messages >= 3:
                            await self.api.post_group_msg(msg.group_id, text="您今日留言已达上限(3条)，请明天再来~")
                            return
                        
                        # 创建留言记录
                        message_record = {
                            "user_id": msg.user_id,
                            "nickname": msg.sender.nickname,
                            "group_id": msg.group_id,
                            "content": content,
                            "time": current_time
                        }
                        
                        # 添加新留言
                        self.message_records[msg.group_id].append(message_record)
                        
                        # 保存留言到配置
                        if "config" not in self.data:
                            self.data["config"] = {}
                        self.data["config"]["message_records"] = self.message_records
                        await self.save_config("message_records", self.message_records)
                        
                        # 计算用户当天剩余留言次数
                        remaining = 3 - (user_today_messages + 1)
                        
                        # 给用户反馈
                        await self.api.post_group_msg(msg.group_id, text=f"留言已保存，您今日还可以留言{remaining}次")
                        _log.info(f"用户 {msg.user_id} 在群 {msg.group_id} 添加了留言，今日第{user_today_messages+1}条")
                    except Exception as e:
                        _log.error(f"保存留言时出错: {e}")
                        import traceback
                        _log.error(traceback.format_exc())  # 添加详细的错误跟踪
                        await self.api.post_group_msg(msg.group_id, text="留言保存失败，请稍后再试")
                else:
                    await self.api.post_group_msg(msg.group_id, text="请提供留言内容，格式：留言+内容")
                return
                  
            return


    async def check_user_permission(self, group_id, user_id):
        """检测用户是否为管理员或群主"""
        try:
            # 获取群成员信息
            member_info = await self.api.get_group_member_info(group_id=group_id, user_id=user_id,no_cache=False)
            if member_info and 'data' in member_info:
                role = member_info['data'].get('role', '')
                return role in ['admin']  # 群主或管理员
            return False
        except Exception as e:
            _log.error(f"检测用户权限出错: {e}")
            return False

    async def check_image_flood(self, msg: GroupMessage):
        """检测用户是否在短时间内发送过多图片，如果是则禁言"""
        try:
            # 检测消息中是否包含图片
            has_image = False
            message_content = msg.message
            status = False
            
            # 解析消息内容，检测是否包含图片
            if isinstance(message_content, list):
                for item in message_content:
                    if isinstance(item, dict) and (item.get('type') == 'image' or item.get('type') == 'video' or item.get('type') == 'face'):
                        has_image = True
                        break
            
            if has_image:
                current_time = time.time()
                group_id = msg.group_id
                user_id = msg.user_id
                
                # 初始化记录（如果不存在）
                if group_id not in self.image_records:
                    self.image_records[group_id] = {}
                if user_id not in self.image_records[group_id]:
                    self.image_records[group_id][user_id] = []
                
                # 添加冷却期检查，避免同一次刷屏被多次计算
                # 检查是否在冷却期内（上次处罚后的30秒内）
                cooldown_key = f"{group_id}_{user_id}_cooldown"
                if hasattr(self, cooldown_key) and current_time - getattr(self, cooldown_key) < 30:
                    # 在冷却期内，不进行处罚
                    _log.info(f"用户 {user_id} 在群 {group_id} 发送图片，但在冷却期内，跳过处罚")
                    return False
                
                # 清理过期记录
                self.image_records[group_id][user_id] = [
                    record for record in self.image_records[group_id][user_id]
                    if current_time - record < self.image_window
                ]
                
                # 添加新记录
                self.image_records[group_id][user_id].append(current_time)
                
                # 检测是否超过数量
                if len(self.image_records[group_id][user_id]) >= self.image_threshold:
                    # 设置冷却标记，避免短时间内多次处罚
                    setattr(self, cooldown_key, current_time)
                    
                    # 获取用户的刷屏次数（在处罚前）
                    spam_count = 0
                    for group_data in self.spam_counts:
                        if group_data['group_id'] == group_id:
                            for user_data in group_data['users']:
                                if user_data['user_id'] == user_id:
                                    spam_count = user_data['number']
                                    break
                            break
                    
                    # 为当前用户记录刷屏次数加1（一次惩罚只记一次）
                    # 查找该群组是否存在于刷屏记录中
                    group_found = False
                    for group_data in self.spam_counts:
                        if group_data['group_id'] == group_id:
                            # 找到群组，查找用户
                            group_found = True
                            user_found = False
                            for user_data in group_data['users']:
                                if user_data['user_id'] == user_id:
                                    # 找到用户，增加计数
                                    user_data['number'] += 1
                                    user_found = True
                                    break
                            
                            # 如果未找到用户，添加新用户记录
                            if not user_found:
                                group_data['users'].append({'user_id': user_id, 'number': 1})
                            break
                    
                    # 如果未找到群组，添加新群组记录
                    if not group_found:
                        self.spam_counts.append({
                            'group_id': group_id,
                            'users': [{'user_id': user_id, 'number': 1}]
                        })
                        spam_count = 0  # 如果是新记录，则刷屏次数为0（+1后为1）
                    
                    # 刷屏次数加1后重新获取
                    spam_count += 1
                    
                    # 根据刷屏次数决定处罚力度
                    if spam_count == 1:
                        # 第一次：禁言10分钟
                        duration = self.ban_duration_first
                        punishment = f"禁言{duration//60}分钟"
                        is_ban=await self.api.get_group_member_info(group_id=group_id, user_id=user_id,no_cache=False)
                        if is_ban.get("data").get("shut_up_timestamp")==0 or is_ban.get("data").get("last_sent_time")>is_ban.get("data").get("shut_up_timestamp"):
                            await self.api.set_group_ban(group_id=group_id, user_id=user_id, duration=duration)
                            status=True
                    elif spam_count == 2:
                        # 第二次：禁言1小时
                        duration = self.ban_duration_second
                        punishment = f"禁言{duration//3600}小时"
                        is_ban=await self.api.get_group_member_info(group_id=group_id, user_id=user_id,no_cache=False)
                        if is_ban.get("data").get("shut_up_timestamp")==0 or is_ban.get("data").get("last_sent_time")>is_ban.get("data").get("shut_up_timestamp"):
                            await self.api.set_group_ban(group_id=group_id, user_id=user_id, duration=duration)
                            status=True
                    else:
                        # 第三次：踢出并拉黑
                        punishment = "踢出群聊并拉黑"
                        # 先尝试踢出
                        try:
                            await self.api.set_group_kick(
                                group_id=group_id,
                                user_id=user_id,
                                reject_add_request=True  # 拒绝此人的加群请求
                            )
                            # 添加到黑名单
                            self.blacklist.add(user_id)
                            # 保存黑名单到配置
                            await self.save_config("blacklist", list(self.blacklist))
                            status=True
                        except Exception as e:
                            _log.error(f"踢出用户失败: {e}")
                            # 如果踢出失败，仍然进行最长时间禁言
                            await self.api.set_group_ban(group_id=group_id, user_id=user_id, duration=30*24*3600)  # 30天
                            punishment = "禁言30天(踢出失败)"
                            status=True
                    
                    # 发送提醒消息
                    if status:
                        message = MessageChain([
                        At(user_id),
                        Text(f" 检测到您刷屏，这是第{spam_count}次刷屏，已被{punishment}！第一次刷屏禁言10分钟，第二次刷屏禁言1小时，第三次刷屏踢出并拉黑")
                    ])
                    await self.api.post_group_msg(group_id=group_id, rtf=message)
                    
                    # 清空该用户记录
                    self.image_records[group_id][user_id] = []
                    
                    _log.info(f"用户 {user_id} 在群 {group_id} 第{spam_count}次刷屏，处罚: {punishment}")
                    is_ban=await self.api.get_group_member_info(group_id=group_id, user_id=user_id,no_cache=False)
                    if is_ban.get("data").get("shut_up_timestamp")==0:
                        message = MessageChain([
                        At(user_id),
                        Text(f"禁言失败,请管理员手动{punishment}")
                    ])
                        await self.api.post_group_msg(group_id=group_id, rtf=message)
                    
                    # 保存刷屏记录到配置
                    await self.save_spam_data()
                    
                    # 如果用户被踢出，从记录中移除
                    if spam_count >= 3:
                        # 从新格式的刷屏记录中移除
                        for group_data in self.spam_counts:
                            if group_data['group_id'] == group_id:
                                group_data['users'] = [u for u in group_data['users'] if u['user_id'] != user_id]
                                break
                        
                        # 清除图片记录
                        if user_id in self.image_records[group_id]:
                            del self.image_records[group_id][user_id]
                        
                        # 保存更新后的数据
                        await self.save_spam_data()
                    
                return status
                
                return False
        except Exception as e:
            _log.error(f"检测刷屏出错: {e}")
            import traceback
            _log.error(traceback.format_exc())
            return False

    async def set_group_all_mute(self, group_id, enable=True):
        """设置群全员禁言状态"""
        try:
            # 使用正确的参数格式调用API
            await self.api.set_group_whole_ban(
                group_id=int(group_id),  # 确保group_id是整数
                enable=enable  # 布尔值，True表示开启，False表示关闭
            )
            
            # 使用动态时间信息
            if enable:
                unmute_time = f"{self.unmute_hour:02d}:{self.unmute_minute:02d}"
                message = f"大家好,为了大家有一个良好的休息环境，现在开启全员禁言。"
            else:
                mute_time = f"{self.mute_hour:02d}:{self.mute_minute:02d}"
                message = f"大家好,全员禁言已解除!"
            
            await self.api.post_group_msg(group_id=group_id, text=message)
            
            if enable:
                self.all_mute_groups.add(str(group_id))  # 存储为字符串，确保集合操作正确
            else:
                self.all_mute_groups.discard(str(group_id))
                
            _log.info(f"群 {group_id} {'开启' if enable else '关闭'}全员禁言")
        except Exception as e:
            _log.error(f"设置全员禁言出错: {e}")
            _log.error(f"参数: group_id={group_id}, enable={enable}, 类型: {type(group_id)}, {type(enable)}")

    async def get_group_list(self):
        """获取机器人加入的群列表"""
        try:
            response = await self.api.get_group_list()
            return response.get('data', [])
        except Exception as e:
            _log.error(f"获取群列表出错: {e}")
            return []

    @bot.private_event()
    async def on_private_message(self, msg: PrivateMessage):
        _log.info(f"收到私聊消息: {msg.raw_message}")
        if msg.raw_message == "测试":
            await msg.reply("NcatBot 插件私聊测试成功喵~")
            
        # root用户管理命令
        if msg.user_id == self.root_user:

            if msg.raw_message == "查看留言" or msg.raw_message.startswith("查看留言+"):
                try:
                    # 确保留言记录存在并且是字典类型
                    if not hasattr(self, "message_records") or not self.message_records:
                        await self.api.post_private_msg(user_id=msg.user_id, text="目前没有任何留言记录")
                        return
                    
                    # 检查是否需要按时间筛选
                    time_filter = None
                    current_time = int(time.time())
                    filter_name = "全部"
                    
                    if msg.raw_message.startswith("查看留言+"):
                        time_range = msg.raw_message[5:].strip()
                        if time_range == "本日":
                            # 今天0点的时间戳
                            today = time.localtime(current_time)
                            day_start = time.mktime((today.tm_year, today.tm_mon, today.tm_mday, 0, 0, 0, 0, 0, 0))
                            time_filter = day_start
                            filter_name = "今日"
                        elif time_range == "本周":
                            # 本周一0点的时间戳
                            today = time.localtime(current_time)
                            days_since_monday = today.tm_wday  # 0是周一，6是周日
                            monday = current_time - days_since_monday * 86400
                            monday_struct = time.localtime(monday)
                            week_start = time.mktime((monday_struct.tm_year, monday_struct.tm_mon, monday_struct.tm_mday, 0, 0, 0, 0, 0, 0))
                            time_filter = week_start
                            filter_name = "本周"
                        elif time_range == "本月":
                            # 本月1号0点的时间戳
                            today = time.localtime(current_time)
                            month_start = time.mktime((today.tm_year, today.tm_mon, 1, 0, 0, 0, 0, 0, 0))
                            time_filter = month_start
                            filter_name = "本月"
                        else:
                            await self.api.post_private_msg(user_id=msg.user_id, text="时间范围格式错误，可选：本日、本周、本月")
                            return
                    
                    # 提取所有留言并按时间筛选
                    all_messages = []
                    for group_id, messages in self.message_records.items():
                        for message in messages:
                            all_messages.append(message)
                    
                    # 应用时间筛选
                    if time_filter:
                        all_messages = [m for m in all_messages if m.get("time", 0) >= time_filter]
                        if not all_messages:
                            await self.api.post_private_msg(user_id=msg.user_id, text=f"{filter_name}没有留言记录")
                            return
                    
                    # 按群组整理留言
                    group_to_messages = {}
                    for message in all_messages:
                        group_id = message.get("group_id")
                        if group_id not in group_to_messages:
                            group_to_messages[group_id] = []
                        group_to_messages[group_id].append(message)
                    
                    # 构建回复消息
                    response = f"{filter_name}留言记录汇总：\n\n"
                    
                    # 获取群列表（如果可用）
                    group_names = {}
                    try:
                        group_list = await self.api.get_group_list()
                        if group_list and "data" in group_list:
                            for group in group_list["data"]:
                                group_names[group.get("group_id")] = group.get("group_name", "未知群组")
                    except Exception as e:
                        _log.warning(f"获取群组列表失败: {e}，将使用群号代替群名")
                    
                    # 为每个群组构建留言列表
                    for group_id, messages in group_to_messages.items():
                        # 按时间倒序排序
                        messages.sort(key=lambda x: x.get("time", 0), reverse=True)
                        
                        # 获取群名称
                        group_name = group_names.get(group_id, f"群组 {group_id}")
                        
                        response += f"【{group_name}】(共{len(messages)}条留言)\n"
                        
                        # 每个群最多显示5条最新留言
                        display_messages = messages[:5]
                        
                        for i, m in enumerate(display_messages, 1):
                            time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(m.get("time", 0)))
                            nickname = m.get("nickname", "未知用户")
                            user_id = m.get("user_id", "未知ID")
                            content = m.get("content", "")
                            response += f"{i}. {nickname}({user_id}) {time_str}\n   {content}\n"
                        
                        if len(messages) > 5:
                            response += f"   ...还有{len(messages)-5}条留言未显示\n"
                        response += "\n"
                    
                    # 添加总计信息
                    total_count = sum(len(msgs) for msgs in group_to_messages.values())
                    response += f"总计: {len(group_to_messages)}个群组，{total_count}条留言"
                    
                    await self.api.post_private_msg(user_id=msg.user_id, text=response)
                except Exception as e:
                    _log.error(f"查看留言时出错: {e}")
                    import traceback
                    _log.error(traceback.format_exc())  # 添加详细错误日志
                    await self.api.post_private_msg(user_id=msg.user_id, text=f"查看留言出错: {str(e)}")
                return
                
            if msg.raw_message == "清空留言" or msg.raw_message.startswith("清空留言+"):
                try:
                    # 确保留言记录存在
                    if not hasattr(self, "message_records") or not self.message_records:
                        await self.api.post_private_msg(user_id=msg.user_id, text="目前没有任何留言记录")
                        return
                    
                    # 默认清除所有群的所有留言（超管私聊环境）
                    target_group_id = None
                    time_filter = None
                    filter_name = "所有群的"
                    
                    # 检查是否有特定参数
                    if msg.raw_message.startswith("清空留言+"):
                        params = msg.raw_message[5:].strip().split("+")
                        
                        # 可以指定群号
                        if len(params) >= 1:
                            if params[0].isdigit():
                                target_group_id = int(params[0])
                                filter_name = f"群 {target_group_id} 的"
                                params = params[1:] if len(params) > 1 else []
                            elif params[0] == "全部":
                                target_group_id = None
                                filter_name = "所有群的"
                                params = params[1:] if len(params) > 1 else []
                        
                        # 检查是否有时间范围参数
                        if len(params) >= 1:
                            time_range = params[0]
                            current_time = int(time.time())
                            
                            if time_range == "本日":
                                # 今天0点的时间戳
                                today = time.localtime(current_time)
                                day_start = time.mktime((today.tm_year, today.tm_mon, today.tm_mday, 0, 0, 0, 0, 0, 0))
                                time_filter = day_start
                                filter_name += "今日"
                            elif time_range == "本周":
                                # 本周一0点的时间戳
                                today = time.localtime(current_time)
                                days_since_monday = today.tm_wday  # 0是周一，6是周日
                                monday = current_time - days_since_monday * 86400
                                monday_struct = time.localtime(monday)
                                week_start = time.mktime((monday_struct.tm_year, monday_struct.tm_mon, monday_struct.tm_mday, 0, 0, 0, 0, 0, 0))
                                time_filter = week_start
                                filter_name += "本周"
                            elif time_range == "本月":
                                # 本月1号0点的时间戳
                                today = time.localtime(current_time)
                                month_start = time.mktime((today.tm_year, today.tm_mon, 1, 0, 0, 0, 0, 0, 0))
                                time_filter = month_start
                                filter_name += "本月"
                            elif time_range != "全部":
                                await self.api.post_private_msg(user_id=msg.user_id, text="时间范围格式错误，可选：本日、本周、本月、全部")
                                return
                    
                    # 统计删除数量
                    original_total = sum(len(messages) for messages in self.message_records.values())
                    
                    # 针对不同筛选条件清除留言
                    if target_group_id is not None:
                        # 清除特定群的留言
                        if target_group_id in self.message_records:
                            if time_filter is not None:
                                # 按时间过滤特定群留言
                                self.message_records[target_group_id] = [
                                    m for m in self.message_records[target_group_id] 
                                    if m.get("time", 0) < time_filter
                                ]
                            else:
                                # 清除特定群的所有留言
                                self.message_records[target_group_id] = []
                    else:
                        # 清除所有群的留言
                        if time_filter is not None:
                            # 按时间过滤所有群留言
                            for group_id in self.message_records:
                                self.message_records[group_id] = [
                                    m for m in self.message_records[group_id] 
                                    if m.get("time", 0) < time_filter
                                ]
                        else:
                            # 清除所有留言
                            self.message_records = {}
                    
                    # 计算清除的留言数量
                    current_total = sum(len(messages) for messages in self.message_records.values())
                    removed_count = original_total - current_total
                    
                    # 保存更新后的留言到配置
                    if "config" not in self.data:
                        self.data["config"] = {}
                    self.data["config"]["message_records"] = self.message_records
                    await self.save_config("message_records", self.message_records)
                    
                    # 发送结果通知
                    result_msg = f"已清空{filter_name}留言记录，共删除 {removed_count} 条留言"
                    await self.api.post_private_msg(user_id=msg.user_id, text=result_msg)
                except Exception as e:
                    _log.error(f"清空留言出错: {e}")
                    import traceback
                    _log.error(traceback.format_exc())  # 添加详细错误日志
                    await self.api.post_private_msg(user_id=msg.user_id, text=f"清空留言出错: {str(e)}")
                return
            
            # 查看当前群聊列表
            if msg.raw_message == "查看群聊列表":
                group_list_str = "当前监控的群聊列表:\n"
                for i, group_id in enumerate(self.group_ids):
                    group_list_str += f"{i+1}. {group_id}\n"
                await msg.reply(group_list_str)
                
            # 添加群聊
            if msg.raw_message.startswith("添加群聊"):
                try:
                    parts = msg.raw_message.split()
                    if len(parts) >= 2:
                        new_group_id = int(parts[1])
                        if new_group_id not in self.group_ids:
                            self.group_ids.append(new_group_id)
                            # 保存群组ID到配置
                            self.register_config("group_ids", self.group_ids)
                            await msg.reply(f"已添加群聊: {new_group_id}")
                        else:
                            await msg.reply(f"群聊 {new_group_id} 已在列表中")
                    else:
                        await msg.reply("格式错误，正确格式：添加群聊 群号")
                except Exception as e:
                    await msg.reply(f"添加群聊出错: {str(e)}")
                    
            # 删除群聊
            if msg.raw_message.startswith("删除群聊"):
                try:
                    parts = msg.raw_message.split()
                    if len(parts) >= 2:
                        group_id = int(parts[1])
                        if group_id in self.group_ids:
                            self.group_ids.remove(group_id)
                            # 保存群组ID到配置
                            self.register_config("group_ids", self.group_ids)
                            await msg.reply(f"已删除群聊: {group_id}")
                        else:
                            await msg.reply(f"群聊 {group_id} 不在列表中")
                    else:
                        await msg.reply("格式错误，正确格式：删除群聊 群号")
                except Exception as e:
                    await msg.reply(f"删除群聊出错: {str(e)}")
                    
            # 清空群聊列表
            if msg.raw_message == "清空群聊列表":
                self.group_ids = []
                # 保存群组ID到配置
                self.register_config("group_ids", self.group_ids)
                await msg.reply("已清空群聊列表")
                
            # 清空刷屏记录
            if msg.raw_message == "清空刷屏记录":
                self.spam_counts = []
                await self.save_spam_data()
                await msg.reply("已清空所有刷屏记录")
                
            # 查看刷屏记录
            if msg.raw_message == "查看刷屏记录":
                if not self.spam_counts:
                    await msg.reply("当前没有刷屏记录")
                    return
                    
                record_str = "刷屏记录统计：\n"
                for group_data in self.spam_counts:
                    if group_data['users']:
                        record_str += f"群 {group_data['group_id']}：\n"
                        for user_data in group_data['users']:
                            record_str += f"  用户 {user_data['user_id']}：{user_data['number']}次\n"
                
                await msg.reply(record_str)
    

    @bot.notice_event()
    async def on_notice_message(self,msg:dict):
        _log.info(f"收到通知消息: {msg}")
        # 处理群成员变更通知
        print(msg)
        if msg.notice_type == 'group_increase':
            increase_status=await self.handle_group_increase(msg)
            if increase_status:
                _log.info(f"群成员变更通知处理成功")
                return
            
    async def handle_group_increase(self,msg:dict):
        _log.info(f"收到群成员变更通知: {msg}")
        group_id = msg.group_id
        user_id = msg.user_id
        user_info = await self.api.get_user_card(user_id=user_id)
        message = MessageChain([
            At(user_id),
            Image("https://q1.qlogo.cn/g?b=qq&nk="+str(user_id)+"&s=100"),
            Text(f"欢迎你加入群聊\n"),
            Text("壁纸获取请查看群公告\n"),
            Text("请遵守群规，不发广告\n"),
            Text("发送:功能列表 查看机器人功能")
        ])
        await self.api.post_group_msg(group_id=group_id, rtf=message)
        return True
        

    async def update_scheduled_tasks(self):
        """更新定时任务，当修改时间后需要重新设置任务"""
        try:
            # 先移除旧的定时任务
            self.remove_scheduled_task("daily_mute")
            self.remove_scheduled_task("daily_unmute")
            
            # 重新添加定时任务
            mute_time = f"{self.mute_hour:02d}:{self.mute_minute:02d}"
            self.add_scheduled_task(
                job_func=self.execute_all_mute,
                name="daily_mute",
                interval=mute_time
            )
            
            unmute_time = f"{self.unmute_hour:02d}:{self.unmute_minute:02d}"
            self.add_scheduled_task(
                job_func=self.execute_all_unmute,
                name="daily_unmute",
                interval=unmute_time
            )
            
            # 保存设置到配置
            await self.save_config("mute_hour", self.mute_hour)
            await self.save_config("mute_minute", self.mute_minute)
            await self.save_config("unmute_hour", self.unmute_hour)
            await self.save_config("unmute_minute", self.unmute_minute)
            
            _log.info(f"定时全员禁言任务已更新: 每天 {mute_time} 开启，{unmute_time} 解除")
            return True
        except Exception as e:
            _log.error(f"更新定时任务失败: {e}")
            import traceback
            _log.error(traceback.format_exc())
            return False

    async def on_load(self):
        # 插件加载时执行的操作, 可缺省
        print(f"{self.name} 插件已加载")
        print(f"插件版本: {self.version}")
        self.register_config("info", "测试配置项")
        self.register_user_func("测试用户功能", self.test_user_func, raw_message_filter="tu")
        self.register_admin_func("测试管理员功能", self.test_admin_func, raw_message_filter="ta")
        
        # 加载黑名单
        if "blacklist" in self.data.get("config", {}):
            self.blacklist = set(self.data["config"]["blacklist"])
        else:
            self.register_config("blacklist", [])
            
        # 加载群组ID列表
        if "group_ids" in self.data.get("config", {}):
            self.group_ids = self.data["config"]["group_ids"]
        else:
            self.register_config("group_ids", self.group_ids)
            
        # 加载刷屏相关设置
        if "image_window" in self.data.get("config", {}):
            self.image_window = self.data["config"]["image_window"]
        else:
            self.register_config("image_window", self.image_window)
        
        if "image_threshold" in self.data.get("config", {}):
            self.image_threshold = self.data["config"]["image_threshold"]
        else:
            self.register_config("image_threshold", self.image_threshold)
        
        # 加载禁言时间设置
        if "mute_hour" in self.data.get("config", {}):
            self.mute_hour = self.data["config"]["mute_hour"]
        if "mute_minute" in self.data.get("config", {}):
            self.mute_minute = self.data["config"]["mute_minute"]
        if "unmute_hour" in self.data.get("config", {}):
            self.unmute_hour = self.data["config"]["unmute_hour"]
        if "unmute_minute" in self.data.get("config", {}):
            self.unmute_minute = self.data["config"]["unmute_minute"]
        
        # 加载刷屏相关数据
        _log.info("开始加载刷屏数据...")
        await self.load_spam_data()
        
        # 设置定时任务 - 每天指定时间开启全员禁言
        mute_time = f"{self.mute_hour:02d}:{self.mute_minute:02d}"
        self.add_scheduled_task(
            job_func=self.execute_all_mute,
            name="daily_mute",
            interval=mute_time
        )
        
        # 设置定时任务 - 每天指定时间解除全员禁言
        unmute_time = f"{self.unmute_hour:02d}:{self.unmute_minute:02d}"
        self.add_scheduled_task(
            job_func=self.execute_all_unmute,
            name="daily_unmute",
            interval=unmute_time
        )
        
        _log.info(f"定时全员禁言任务已设置: 每天 {mute_time} 开启，{unmute_time} 解除")
        _log.info(f"刷屏检测设置: 刷屏检测时间={self.image_window}秒, 触发数量={self.image_threshold}张图片")
        
        # 加载违规词检测设置
        if "check_ad_status" in self.data.get("config", {}):
            self.check_ad_status = self.data["config"]["check_ad_status"]
        else:
            self.register_config("check_ad_status", self.check_ad_status)
        
        if "ad_keywords" in self.data.get("config", {}):
            self.ad_keywords = self.data["config"]["ad_keywords"]
        else:
            self.register_config("ad_keywords", self.ad_keywords)
        
        if "ad_ban_duration" in self.data.get("config", {}):
            self.ad_ban_duration = self.data["config"]["ad_ban_duration"]
        else:
            self.register_config("ad_ban_duration", self.ad_ban_duration)
        
        _log.info(f"违规词检测功能已{'开启' if self.check_ad_status else '关闭'}")
        _log.info(f"违规词检测设置: 关键词数量={len(self.ad_keywords)}")

        self.message_records = {}
        config = self.data.get("config", {})
        if "message_records" in config:
            # 确保格式正确
            if isinstance(config["message_records"], dict):
                self.message_records = config["message_records"]
            else:
                _log.warning("留言记录格式不正确，已重置为空")

    async def execute_all_mute(self):
        """执行全员禁言"""
        _log.info("执行全员禁言")
        for group_id in self.group_ids:
            try:
                await self.set_group_all_mute(group_id, True)
            except Exception as e:
                _log.error(f"为群 {group_id} 执行全员禁言出错: {e}")

    async def execute_all_unmute(self):
        """执行全员解禁"""
        _log.info("执行全员解禁")
        for group_id in self.group_ids:
            try:
                await self.set_group_all_mute(group_id, False)
            except Exception as e:
                _log.error(f"为群 {group_id} 执行全员解禁出错: {e}")
    
    async def test_user_func(self, msg: PrivateMessage):
        await msg.reply(text="用户功能:" + self.data['config']['info'])
    
    async def test_admin_func(self, msg: GroupMessage):
        await msg.reply(text="管理员功能:" + self.data['config']['info'])
    
    async def on_unload(self):
        print(f"{self.name} 插件已卸载")
        # 保存数据确保不丢失
        _log.info("插件卸载，保存刷屏数据...")
        await self.save_spam_data()

    async def save_spam_data(self):
        """保存刷屏相关数据到配置"""
        try:
            # 刷屏数据已经是我们需要的格式，直接保存
            _log.info(f"保存刷屏数据 - 数据内容: {self.spam_counts}")
            
            # 使用新方法保存到配置
            await self.save_config("spam_counts", self.spam_counts)
            
            # 验证是否保存成功
            saved_data = self.data.get("config", {}).get("spam_counts", [])
            _log.info(f"保存后的配置数据: {saved_data}")
            
            _log.info("刷屏记录已保存到配置")
            return True
        except Exception as e:
            _log.error(f"保存刷屏数据出错: {e}")
            import traceback
            _log.error(traceback.format_exc())
            return False

    async def load_spam_data(self):
        """从配置加载刷屏相关数据"""
        try:
            # 加载刷屏计数
            if "spam_counts" in self.data.get("config", {}):
                # 直接加载数据列表
                self.spam_counts = self.data["config"]["spam_counts"]
                
                # 打印加载的数据以便调试
                _log.info(f"加载刷屏数据 - 从配置加载的数据: {self.spam_counts}")
                _log.info(f"已加载刷屏记录，共 {len(self.spam_counts)} 个群")
                
                return True
            else:
                _log.info("配置中没有找到刷屏记录数据")
                self.spam_counts = []  # 初始化为空列表
                return True
        except Exception as e:
            _log.error(f"加载刷屏数据出错: {e}")
            import traceback
            _log.error(traceback.format_exc())
            return False

    async def check_at_owner(self, msg: GroupMessage):
        """检测消息中是否@了群主，如果是则回复群主正在修养中，连续多次@禁言"""
        try:
            status = False
            message_content = msg.message  # 获取消息内容(数组格式)
            
            # 检查是否有@的内容
            at_qq_numbers = []
            if isinstance(message_content, list):
                for item in message_content:
                    if isinstance(item, dict) and item.get('type') == 'at' and 'data' in item:
                        qq_number = item.get('data', {}).get('qq')
                        if qq_number:
                            at_qq_numbers.append(qq_number)
            
            # 如果没有找到at，直接返回
            if not at_qq_numbers:
                return status
                
            # 获取群成员信息，检测哪些被@的用户是群主
            for qq in at_qq_numbers:
                try:
                    # 获取被@用户的信息
                    if int(qq)==self.root_user:
                        # 是群主，回复消息
                        await self.api.post_group_msg(
                            group_id=msg.group_id,
                            text="群主正在修养中，请不要@群主",
                            reply=msg.message_id
                        )
                        _log.info(f"用户 {msg.user_id} 在群 {msg.group_id} @了群主 {qq}，已回复提醒")
                        status = True
                        
                        # 获取最近10条消息历史
                        history = await self.api.get_group_msg_history(
                            group_id=msg.group_id,
                            message_seq=0,
                            count=10,
                            reverse_order=True
                        )
                        
                        # 统计同一用户@群主的次数
                        at_owner_count = 0
                        if 'data' in history and 'messages' in history['data']:
                            for hist_msg in history['data']['messages']:
                                # 检查是否是同一个用户发的消息
                                if hist_msg.get('user_id') == msg.user_id:
                                    # 检查消息内容是否@了群主
                                    message_array = hist_msg.get('message', [])
                                    if isinstance(message_array, list):
                                        for item in message_array:
                                            if (isinstance(item, dict) and 
                                                item.get('type') == 'at' and 
                                                str(item.get('data', {}).get('qq')) == str(qq)):
                                                at_owner_count += 1
                                                break
                                    # 也可以从原始消息中检查
                                    elif f"[CQ:at,qq={qq}]" in hist_msg.get('raw_message', ''):
                                        at_owner_count += 1
                        
                        _log.info(f"用户 {msg.user_id} 在最近10条消息中@群主次数: {at_owner_count}")
                        
                        # 如果同一用户短时间内@群主达到3次及以上，则禁言
                        if at_owner_count >= 3:
                            # 检查用户是否已经被禁言
                            member_info = await self.api.get_group_member_info(
                                group_id=msg.group_id,
                                user_id=msg.user_id,
                                no_cache=False
                            )
                            
                            if member_info.get('data', {}).get('shut_up_timestamp') == 0:
                                # 禁言5分钟(300秒)
                                await self.api.set_group_ban(
                                    group_id=msg.group_id,
                                    user_id=msg.user_id,
                                    duration=300
                                )
                                
                                # 发送禁言提醒
                                await self.api.post_group_msg(
                                    group_id=msg.group_id,
                                    text=f"用户 {msg.user_id} 短时间内多次@群主，已被禁言5分钟"
                                )
                                
                                _log.info(f"用户 {msg.user_id} 在群 {msg.group_id} 短时间内多次@群主，已被禁言5分钟")
                        break
                except Exception as e:
                    _log.error(f"获取群成员信息出错: {e}")
                    continue
            return status
        except Exception as e:
            _log.error(f"检测@群主出错: {e}")
            import traceback
            _log.error(traceback.format_exc())

    async def check_at_robot(self, msg: GroupMessage):
        """检测消息中是否@了机器人"""
        try:
            status = False
            message_content = msg.message  # 获取消息内容(数组格式)
            # 检查是否有@的内容
            at_qq_numbers = []
            if isinstance(message_content, list):
                for item in message_content:
                    if isinstance(item, dict) and item.get('type') == 'at' and 'data' in item:
                        qq_number = item.get('data', {}).get('qq')
                        if qq_number:
                            at_qq_numbers.append(qq_number)
            
            # 如果没有找到at，直接返回
            if not at_qq_numbers:
                return status
                
            for qq in at_qq_numbers:
                try:
                    # 确保两边都是整数类型进行比较
                    qq_int = int(str(qq).strip())  # 先转字符串并去除可能的空格，再转整数
                    bt_uin_int = int(str(config.bt_uin).strip())
                    
                    if qq_int == bt_uin_int:
                        status = True
                        await self.api.post_group_msg(
                            group_id=msg.group_id,
                            text=f"查看你身份组可使用的机器人功能请发送:功能列表"
                        )
                        break
                except Exception as e:
                    print(f"处理QQ号时出错: {str(e)}")
                    continue
            return status
        except Exception as e:
            _log.error(f"检测@机器人出错: {e}")
            import traceback
            _log.error(traceback.format_exc())

    async def check_keywords_and_send_image(self, msg: GroupMessage):
        """检测消息中是否包含关键词，如包含则调用API获取图片并发送"""
        try:
            raw_message = msg.raw_message
            api_type = None
            # 检测关键词
            if "黑丝" in raw_message:
                api_type = "heisi"
            elif "白丝" in raw_message:
                api_type = "baisi"
            elif "JK" in raw_message.upper() or "jk" in raw_message.lower():
                api_type = "jk"
            
            # 如果检测到关键词，调用API
            if api_type:
                import requests
                import asyncio
                
                api_url = f"https://v2.xxapi.cn/api/{api_type}"
                
                # 将同步请求包装在异步函数中执行
                def make_request():
                    try:
                        response = requests.get(api_url)
                        return response
                    except Exception as e:
                        _log.error(f"请求API出错: {e}")
                        return None
                
                # 在异步环境中执行同步函数
                response = await asyncio.get_event_loop().run_in_executor(None, make_request)
                
                if response and response.status_code == 200:
                    data = response.json()
                    print(data)
                    if data.get("code") == 200:
                        # 获取图片URL
                        image_url = data.get("data")
                        
                        # 修改创建Image元素的方式
                        # 方法1: 尝试直接传递URL字符串
                        image_message = MessageChain([
                            Image(image_url)
                        ])
                        
                        # 如果上面的方法不行，尝试下面的备选方案
                        # 方法2: 查看是否需要使用特定参数名
                        # image_message = MessageChain([
                        #    Image(file=image_url)
                        # ])
                        
                        # 方法3: 创建字典格式的消息
                        # image_message = [{"type": "image", "data": {"file": image_url}}]
                        
                        await self.api.post_group_msg(group_id=msg.group_id, rtf=image_message)
                        _log.info(f"成功发送{api_type}图片: {image_url}")
                        return True
                    else:
                        # API返回错误
                        await self.api.post_group_msg(
                            group_id=msg.group_id, 
                            text=f"请求{api_type}图片失败: API返回错误"
                        )
                        return True
                else:
                    # 请求失败
                    await self.api.post_group_msg(
                        group_id=msg.group_id, 
                        text=f"请求{api_type}图片失败: 网络错误"
                    )
                    return True
            else:
                return False
        except Exception as e:
            _log.error(f"获取图片出错: {e}")
            await self.api.post_group_msg(
                group_id=msg.group_id, 
                text="请求图片失败: 内部错误"
            )
            import traceback
            _log.error(traceback.format_exc())
        
    async def save_config(self, key, value):
        """保存配置并确保更新现有值"""
        try:
            # 直接更新数据结构
            if 'config' not in self.data:
                self.data['config'] = {}
            self.data['config'][key] = value
            
            # 调用 register_config 方法
            self.register_config(key, value)
            
            # 可以添加日志确认保存
            _log.info(f"配置 {key} 已更新为: {value}")
            return True
        except Exception as e:
            _log.error(f"保存配置 {key} 失败: {e}")
            import traceback
            _log.error(traceback.format_exc())
            return False
        
    async def check_advertisement(self, msg: GroupMessage):
        """检测消息是否包含违规词，如果是则进行处罚"""
        try:
            # 如果违规词检测功能已关闭，直接返回
            if not self.check_ad_status:
                return False
            if "删除违规词" in msg.raw_message:
                return False
            
            raw_message = msg.raw_message.lower()  # 转小写以便检测
            group_id = msg.group_id
            user_id = msg.user_id

            # 检测是否包含关键词
            has_ad_keyword = any(keyword.lower() in raw_message for keyword in self.ad_keywords)
            

            # 如果检测到违规词内容
            if has_ad_keyword:
                # 检测是否是管理员
                is_admin = await self.check_user_permission(group_id, user_id)
                if is_admin:
                    await self.api.post_private_msg(user_id=self.root_user, text="检测到有管理员在群聊中发送了违规词内容，内容是"+raw_message)
                    return False
                
                # 判断是否已经在禁言状态
                member_info = await self.api.get_group_member_info(
                    group_id=group_id, 
                    user_id=user_id,
                    no_cache=False
                )
                
                # 如果用户已经被禁言，则不再重复处罚
                if member_info.get('data', {}).get('shut_up_timestamp') != 0:
                    return False
                
                # 增加用户发违规词计数
                self.ad_records[group_id][user_id] += 1
                ad_count = self.ad_records[group_id][user_id]
                
                await self.api.delete_msg(message_id=msg.message_id)  # 删除消息

                # 根据次数决定处罚力度
                if ad_count == 1:
                    # 第一次发违规词：禁言
                    duration = self.ad_ban_duration
                    punishment = f"禁言{duration//60}分钟"
                    await self.api.set_group_ban(group_id=group_id, user_id=user_id, duration=duration)
                elif ad_count == 2:
                    # 第二次发违规词：延长禁言时间
                    duration = self.ad_ban_duration * 3  # 30分钟
                    punishment = f"禁言{duration//60}分钟"
                    await self.api.set_group_ban(group_id=group_id, user_id=user_id, duration=duration)
                else:
                    # 第三次及以上：踢出并拉黑
                    punishment = "踢出群聊并拉黑"
                    try:
                        await self.api.set_group_kick(
                            group_id=group_id,
                            user_id=user_id,
                            reject_add_request=True  # 拒绝此人的加群请求
                        )
                        # 添加到黑名单
                        self.blacklist.add(user_id)
                        # 保存黑名单到配置
                        await self.save_config("blacklist", list(self.blacklist))
                    except Exception as e:
                        _log.error(f"踢出用户失败: {e}")
                        # 如果踢出失败，仍然进行最长时间禁言
                        duration = 30*24*3600  # 30天
                        await self.api.set_group_ban(group_id=group_id, user_id=user_id, duration=duration)
                        punishment = "禁言30天(踢出失败)"
                
                # 发送提醒消息
                await self.api.post_group_msg(
                    group_id=group_id,
                    text=f"检测到用户 {user_id} 发言包含违规词，这是第{ad_count}次违规，已被{punishment}。"
                )
                
                _log.info(f"用户 {user_id} 在群 {group_id} 第{ad_count}次发违规词，处罚: {punishment}")
                return True
            
            return False
        except Exception as e:
            _log.error(f"检测违规词出错: {e}")
            import traceback
            _log.error(traceback.format_exc())
            return False
        
